package cn.goour.web.sys.controller.settings

import cn.goour.web.base.`interface`.ValidModifying
import cn.goour.web.base.entity.Msg
import cn.goour.web.base.entity.PageInfo
import cn.goour.web.base.exception.BackJsonBeanValidFailException
import cn.goour.web.sys.entity.User
import cn.goour.web.sys.entity.type.HttpHeader
import cn.goour.web.sys.service.UserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.Errors
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import javax.annotation.PostConstruct

@RestController
@RequestMapping("/admin/settings/users")
open class UserController {

    @Autowired private
    lateinit var userService: UserService

    @GetMapping("", headers = arrayOf(HttpHeader.Ajax))
    open fun list(@Validated pageInfo: PageInfo, errors: Errors): Msg {
        if (errors.hasErrors()) {
            throw BackJsonBeanValidFailException(errors)
        }
        val list = userService.getList(pageInfo)
        return Msg(list)
    }

    @PutMapping("", headers = arrayOf(HttpHeader.Ajax))
    open fun update(@Validated(ValidModifying::class) user: User, errors: Errors): Msg {
        if (errors.hasErrors()) {
            throw BackJsonBeanValidFailException(errors)
        }
        userService.update(user)
        return Msg()
    }

    @DeleteMapping("", headers = arrayOf(HttpHeader.Ajax))
    open fun del(@RequestParam("id[]") id: Array<Int>): Msg {
        val msg = try {
            userService.delete(id)
            Msg()
        } catch (e: Exception) {
            e.printStackTrace()
            Msg.error(e)
        }
        return msg
    }

    init {
        logger.info("Initialized ${this.javaClass.simpleName}...")
    }

    @PostConstruct
    open fun post() {
        logger.info("PostConstruct ${this.javaClass.simpleName}...")
    }

    companion object {
        private val logger = LoggerFactory.getLogger(UserController::class.java)
    }
}